package com.second.app.thread.tongxin;

import java.util.ArrayList;
import java.util.List;

public class ListDemo {

    public static void main(String[] args) {
        TargetDemo targetDemo = new TargetDemo();
        targetDemo.setFlag(true);
        new Thread(targetDemo,"线程A").start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        targetDemo.setFlag(false);
        new Thread(targetDemo,"线程B").start();

    }
}


class TargetDemo implements Runnable {

    public Object lock = new Object();

    private boolean flag;

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override

    public void run() {

        if(flag){
            doAMethod();
        }else {
            doBMethod();
        }
    }


    private void doAMethod() {
        try {
            synchronized (lock){
                if(MyList.size()!=5){
                    System.out.println("wait begin"+System.currentTimeMillis());
                    lock.wait();
                    System.out.println("wait end"+System.currentTimeMillis());
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void doBMethod() {
        synchronized (lock){
            for (int i = 0; i <10; i++) {
                MyList.add();
                if(MyList.size()==5){
                    lock.notify();
                    System.out.println("发出通知了");
                }
                System.out.println("添加了"+(i+1)+" 个元素");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

class MyList {

    private static List<String> list = new ArrayList<>();

    public static void add() {
        list.add("anything");
    }

    public static int size() {
        return list.size();
    }
}
